package com.qf.dao.impl;

import com.qf.dao.OrderDao;
import com.qf.pojo.Order;
import com.qf.pojo.OrderItem;
import com.qf.utils.DruidJdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author 高圆圆
 * @date 2023/1/5 15:58
 * 订单的数据访问接口实现
 */
public class OrderDaoImpl  implements OrderDao {
    /**
     * 插入订单
     * @param order 订单实体
     * @return 返回影响的行数
     */



    @Override
    public int insertOrder(Order order) throws SQLException {
        //执行对象
        //QueryRunner(DataSource ds) --->属于自动提交

        //数据库访问--手动提交
        //QueryRunner():无参构造方法
        //通过执行对象.update(连接对象,sql,实际参数)


        //QueryRunner qr  = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        QueryRunner qr  = new QueryRunner() ;
        //sql
        String sql = "insert into orders values(?,?,?,?,?,?,?,?)";
        int count = qr.update(DruidJdbcUtils.getConnection() ,sql,
                order.getOid(),
                order.getOrdertime(),
                order.getTotal(),
                order.getState(),
                order.getAddress(),
                order.getName(),
                order.getTelephone(),
                order.getUser().getUid());
        return count;
    }

    /**
     * 插入订单项数据
     * @param orderItem 订单项实体
     * @return 返回影响的行数
     */
    @Override
    public int insertOrderItem(OrderItem orderItem) throws SQLException {
        //执行对象
//        QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        QueryRunner qr = new QueryRunner() ;
        //sql
        String sql = "insert into orderitem values(?,?,?,?,?)" ;
        int count = qr.update(DruidJdbcUtils.getConnection(),sql,
                orderItem.getItemid(),
                orderItem.getCount(),
                orderItem.getSubtotal(),
                orderItem.getProduct().getPid(),
                orderItem.getOrder().getOid());
        return count;
    }

    /**
     * 订单数据访问接口 查询指定的订单
     * @param oid 订单编号
     * @return 返回订单实体
     */
    @Override
    public Order selectOrderByOid(String oid) throws SQLException {
        //执行对象
        QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        //sql
        String sql = "select * from orders where oid = ?" ;
        //执行
        Order order = qr.query(sql, new BeanHandler<Order>(Order.class), oid);
        return order;
    }


    /**
     * 数据访问接口更新订单
     * @param order 订单实体
     * @return
     */
    @Override
    public int updateOrder(Order order) throws SQLException {
        QueryRunner qr  = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        //sql
        String sql  ="update orders set state = ? where oid = ?" ;
        int count = qr.update(sql, order.getState(), order.getOid());
        return count;
    }
}
